{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "concepts.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-SXDOmR2MXAs"
      },
      "source": [
        "##### Copyright 2020 Google"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "rVd2ZPuLMZn7"
      },
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ],
      "execution_count": 97,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7yGFOotvMe-m"
      },
      "source": [
        "# Quantum chess"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7G6PK002MgEG"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.example.org/cirq/experiments/quantum_chess/concepts\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on QuantumLib</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/ReCirq/blob/master/docs/quantum_chess/concepts.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/quantumlib/ReCirq/blob/master/docs/quantum_chess/concepts.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/ReCirq/docs/quantum_chess/concepts.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TW7je1uhcLw2"
      },
      "source": [
        "This tutorial illustrates some techniques to navigate through challenges of bringing a theoretical quantum algorithm to the reality of NISQ devices.  Quantum Chess serves as an example to demonstrate these ideas without some of the domain knowledge needed in other experiments.  \n",
        "\n",
        "This tutorial assumes basic knowledge of the following:\n",
        "\n",
        "*   Basic quantum computing principles, specifically, what unitary matrices are, and what an $\\text{iSWAP}$ (and $\\sqrt{\\text{iSWAP}}$ gate is)\n",
        "*   The basic movement rules of [Chess](https://en.wikipedia.org/wiki/Chess#Movement) and the [Algebraic notation](https://en.wikipedia.org/wiki/Algebraic_notation_(chess)) method of naming chess squares and moves.\n",
        "\n",
        "\n",
        "![Algebraic notation](https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/SCD_algebraic_notation.svg/242px-SCD_algebraic_notation.svg.png)\n",
        "\n",
        "*   The [Cirq](https://github.com/quantumlib/Cirq) framework for constructing quantum circuits.\n",
        "*   While the tutorial will briefly cover the rules of quantum chess, those who are unfamiliar with this game may [try it out](https://quantumchess.net/play/) or read the exact rules in the [Quantum Chess paper](https://arxiv.org/abs/1906.05836).  You can also find a sample implementation in this repository under `recirq.quantum_chess`.\n",
        "\n",
        "The goal of this tutorial is to illustrate some basic ideas of transforming a theoretical algorithm (such as Quantum Chess) into a real hardware algorithm, without getting lost in details of more complicated domain-specific problems.  \n",
        "\n",
        "The tutorial is split into several parts:\n",
        "\n",
        "1.   **Introduction to Quantum Chess**: how quantum chess maps to qubits and quantum operations\n",
        "2.   **Quantum chess in Cirq**: how to execute these operations using the cirq framework\n",
        "3.   **Handling partial measurement**:  how to handle moves that include measurement that partially collapses the board state\n",
        "4.   **Noise**: how to deal with some simple noise models\n",
        "5.   **Decomposition**: how to decompose gates\n",
        "6.   **Qubit Layout**: how to run circuits when connectivity matters.\n",
        "\n",
        "You will learn about the concepts of **circuit construction**, **post-selection**, **gate decomposition**, **noise**, **optimizers**, and **qubit mappings**."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "49QJ1Lx1en5z"
      },
      "source": [
        "First, let's get started by installing cirq on our colab runtime:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ugH2oPsQM0Po"
      },
      "source": [
        "try:\n",
        "    import recirq\n",
        "except ImportError:\n",
        "    !pip install --quiet git+https://github.com/quantumlib/ReCirq"
      ],
      "execution_count": 98,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "aEvXlXRJih8k"
      },
      "source": [
        "import cirq\n",
        "from typing import Dict, Iterable, Optional, Set"
      ],
      "execution_count": 99,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CXa-yjN6cVYc"
      },
      "source": [
        "## Introduction to Quantum Chess\n",
        "\n",
        "Quantum chess is analogous to the classical game of [Chess](https://en.wikipedia.org/wiki/Chess).  Special rules are added to the game in order to allow for superposition and entanglement of pieces.  This tutorial will go over the basics of the rules in order to show how one might implement them in cirq and convert them to use a hardware device.  The full rule set, including rules for more complicated situations (such as castling and en passant) can be found in the [Quantum Chess paper](https://arxiv.org/abs/1906.05836).  A demo where you can try moves out and play around on a sandbox board and test your knowledge with puzzles is available at [quantumchess.net](https://quantumchess.net/play/).\n",
        "\n",
        "In order to introduce the game, we will first go over how the board is represented and then go over several of the moves."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HN7Wz-xgflaW"
      },
      "source": [
        "### Quantum Chess Board Representation\n",
        "\n",
        "In classical chess, each square can be represented by one bit determining whether the square is empty (0) or occupied (1) as well as short integer or 'enum' to distinguish the color and type of piece (e.g. King, Queen, Knight, Bishop, Rook, or Pawn).  \n",
        "\n",
        "Quantum chess will also use the same classical register to store the type of piece, since each square can only have one type of piece in it.  Since the storage of the piece type is entirely classical, we will ignore it throughout the rest of this tutorial and focus on the quantum aspects of the game.\n",
        "\n",
        "Classical chess squares have only two states.  Each square is either occupied or not.  For a quantum version of the game, we will want to allow a continuous spectrum of possibilities of the square's occupancy, as represented by a quantum bit, or qubit.\n",
        "\n",
        "In quantum chess, each square is represented by a single qubit.  If the qubit is in the |1> state, the square is occupied by a piece.  If the qubit is in the |0> state, the square is empty.\n",
        "\n",
        "A board state will be a set of qubits that represent a set of squares.  We will often consider a board that is smaller than the standard 8x8 board of chess so that we can more easily illustrate concepts.\n",
        "\n",
        "For instance, let's consider a 3x3 board.  This board will have 9 squares (a1, a2, a3, b1, b2, b3, c1, c2, c3).  We will represent this as a 'ket' string such as this, with spaces to denote row boundaries for ease of reading:\n",
        "\n",
        "```\n",
        "|a1a2a3 b1b2b3 c1c2c3 >\n",
        "```\n",
        "\n",
        "For instance, `|000 000 000>` would represent the empty 3x3 board.  `|010 000 000>` would represent a piece on the 'a2' square.  States can also represent boards with multiple pieces.  `|000 000 110>` would represent a board with pieces on both 'c1' and 'c2'.  Each of these three states is denoted as a **basis state**.\n",
        "\n",
        "A state can also be a super-position of board states.  For instance, \n",
        "$\\frac{1}{\\sqrt{2}}$ `( |100 000 000> + |010 000 000> )` represents a piece being in superposition of being on 'a1' and 'a2'.  This tutorial will often drop the normalization factor such as $\\frac{1}{\\sqrt{2}}$ when it doesn't matter to the explanation.\n",
        "\n",
        "\n",
        "#### Additional qubits\n",
        "\n",
        "Note that there are some exceptions that require extra qubits beyond the requirement of one qubit per square.  These extra qubits (often called \"ancilla\" qubits) are needed to store captured pieces and to store extra information, such as whether a path is blocked by a piece.  We will ignore these extra ancilla qubits for now in order to keep the tutorial focused."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AUJfZU5wcMy6"
      },
      "source": [
        "### Quantum Chess Moves\n",
        "\n",
        "We will be studying a subset of possible quantum chess moves in this tutorial.\n",
        "\n",
        "We will primarily consider the following moves to implement on the hardware:\n",
        "\n",
        "#### Basic jump move\n",
        "\n",
        "This maneuver will be applied when we wish to apply a standard chess move to a piece.  This will be how kings and knights move.  In classical chess, we would remove the piece from its original square and then add it to the target square we are moving it to.\n",
        "\n",
        "For quantum chess, we would like to do an analogous operation that preserves any quantum information.  In order to do this, we will swap the two squares.  We will do this by performing an **iSWAP** gate between the two qubits that represent those squares.  Note that this operation will also add a phase of *i* onto the qubits in addition to swapping them, adding a uniquely quantum aspect to the move.\n",
        "\n",
        "![Standard Move](./images/qc_standard_move.png)\n",
        "\n",
        "For example, if we attempt to move a King piece from the 'a1' square to the 'b1' square, we will perform a iSWAP gate between the qubits that represent the 'a1' and 'b1' squares.\n",
        "\n",
        "#### Split move\n",
        "\n",
        "The split move is unique to quantum chess.  This move will be analogous to moving a piece to two different target squares simultaneously.  If we were to then measure the quantum board, we should get a 50% probability of seeing the piece in either of the two target squares.\n",
        "\n",
        "This will be accomplished by doing a $\\sqrt{\\text{iSWAP}}$ between the source and the first target.  This will create an equal superposition between the source and the first target square.  We would finish the move by performing a iSWAP between the source square and second target square.  This will create an equal superposition between the two target squares.\n",
        "\n",
        "![Split Move](./images/qc_split_move1.png)\n",
        "\n",
        "For example, suppose that that we split move a King on 'a1' to the squares 'b1' and 'b2'.  To do this, we would do a $\\sqrt{\\text{iSWAP}}$ between the qubits representing 'a1' and 'b1' followed by an **iSWAP** on the 'a1' and 'b2' qubits.  A short-hand notation for this move is *Ks1^t1t2* for source square s1 and split targets t1 and t2.  This example would be noted as *Ka1^b1b2*.\n",
        "\n",
        "#### Slide move\n",
        "\n",
        "A slide move is how we will move bishops, queens, and rooks.  These pieces move along a straight path, but cannot pass through intervening pieces.  However, in quantum chess, there may be a piece that is in superposition and may or may not block the path of this move.\n",
        "\n",
        "In order to accomplish this move without measuring (and thereby destroying the quantum nature of the game), we will need to **entangle** the two pieces.  The way we will do this is called a \"controlled\" gate.  A [controlled gate](https://en.wikipedia.org/wiki/Quantum_logic_gate#Controlled_(cX_cY_cZ)_gates) is a gate that is only performed if the control qubit(s) are in the `|1>` state.\n",
        "\n",
        "This tutorial will only consider paths that are blocked by one possible piece.  In this case, we will perform a **controlled-iSWAP** between the source square and target square controlled by the square that is potentially blocking the path.\n",
        "\n",
        "![Slide Move](./images/qc_slide_move.png)\n",
        "\n",
        "For example, suppose we are moving a rook from 'a1' to 'c1', but there is a split knight on 'b1'.  To perform this slide move, we would do an iSWAP between the qubits that represent 'a1' and 'c1' controlled by the 'b1' qubit.  This operation can result in two potential states.  Either the rook is on 'c1' and the knight is not on 'b1' (path was open) or, alternatively, the rook is on 'a1' and the knight is on 'b1' (path was blocked).  The quantum board state cannot be described without mentioning the relationship between the 'b1' and 'a1'/'c1' squares, so we can say that those squares are *entangled*.\n",
        "\n",
        "#### Exclusion move\n",
        "\n",
        "It was mentioned earlier that each square must have only one type of piece.  For instance, a square cannot have 0.1 of a knight and 0.5 of a rook.  This would not be allowed.  This is called the 'no double occupancy' rule.  We will use measurement as a tool to prevent this situation and disambiguate the type of the piece.\n",
        "\n",
        "This can happen in a variety of circumstances, but we will only consider the case where a piece attempts to make a legal, standard move into a square with a piece of its own color.  \n",
        "\n",
        "![Exclusion Move](./images/qc_exclusion_move.png)\n",
        "\n",
        "For instance, suppose we attempt to move a king from 'a1' to 'a2' and there is a split knight on the 'a2' square.  We would then need to measure the 'a2' square.  If the measurement is 1, then the knight occupies the square and the king cannot move.  If the measurement is 0, the knight is not on the square and the king moves successfully.  In this case, we have a classical 'mixture' of states.  Half the time, we would get the king on 'a1' and the knight on 'a2'.  The other half of the time, the king would be on 'a2'.  However, since we have measured and projected the state to one of these possibilities, there would be no superposition or entanglement, and this part of the board would be in a classical state (definitively in either one configuration or the other).\n",
        "\n",
        "#### Other moves\n",
        "\n",
        "These four type of moves are enough to illustrate the complexities of translating an abstract algorithm (quantum chess) onto a concrete hardware implementation.  However, those who are curious can see the full rule set in the [Quantum Chess](https://arxiv.org/abs/1906.05836) paper on arXiv, including for capture, en passant, and castling.\n",
        "\n",
        "**Exercise for the reader**: This describes one possible rule set for translating the game of chess into the quantum world.  How might the game change if you use SWAP gates instead of iSWAP gates?  Can you devise ways to tell the two games apart?  Can you think of other methods to create split moves or other interesting alternatives?\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sPDSzod7jXCx"
      },
      "source": [
        "## Quantum Chess Simulation\n",
        "\n",
        "Now that we have introduced the moves of quantum chess and their corresponding circuits, let's look at how we might actually perform our quantum chess moves and circuits in hardware.  We will first start by learning how to implement them in cirq and how to execute them using cirq's built-in simulator.\n",
        "\n",
        "If we consider that a chess board has 64 squares, then the simulation will need 64 qubits.  Since any combination of these bits is a valid basis state of the system, this means that, in order to do a complete simulation, we will need to keep track of $2^{64}$ states, which is something around 10 quintillion states.  This is obviously infeasible.\n",
        "\n",
        "However, most of these positions are unreachable by any common set of moves.  For most reasonable positions, there is a much smaller amount of superposition, so we do not need to keep track of all of those states, since the probability of those states is zero and will remain zero after we make our moves.\n",
        "\n",
        "For example, the initial position is a classical position, so we only need to keep track of one possible state, where the initial squares are in the |1> state and the empty squares are in the |0> state.  After we make a split move, now we have to keep track of two states.  Each successive move on the board will need to tabulate its effect on both of these possible states.\n",
        "\n",
        "**Example**:\n",
        "\n",
        "Let's consider a 3x3 board as defined above with one King piece that starts in the square 'a1'.  This initial state is:\n",
        "\n",
        "```\n",
        "|100 000 000>\n",
        "```\n",
        "\n",
        "Note that, since there are 9 squares, there are $2^9=512$ possible basis states and a position on this board could be a superposition of any of the 512 basis states.  \n",
        "\n",
        "For instance, let's suppose that we now perform a split move from 'a1' to 'b1' and 'b2'.  Then the state will be (ignoring the factor of $i/{\\sqrt{2}}$): \n",
        "\n",
        "```\n",
        "|000 010 000> + |000 100 000>\n",
        "```\n",
        "\n",
        "![Quantum king moves](./images/qc_qking_moves.png)\n",
        "\n",
        "\n",
        "Now, suppose that we make two additional moves.  First, we will split the \"half-king\" on 'b1' to 'c1' and 'c2'.  Next, we will split the 'half king' on 'b2' to 'b3' and 'c3'.\n",
        "\n",
        "So, despite that we have made three split moves that involve almost all of the squares on the board, we still only have to worry about 4 of the 512 states on the board.  The state is now (ignoring the constant factor):\n",
        "\n",
        "```\n",
        "|000 000 100> + |000 000 010> + |000 001 000> + |000 000 001>\n",
        "```\n",
        "\n",
        "Of course, if we continue splitting moves, we will eventually get to a large number of potential states.  However, we will never need to consider all 512 states in this example, since some states can never be reached by a sequence of moves.  For instance, the state `|110 000 000>` represents a king on a1 *and* a king on b1.  There's no way where we can start the board with one king on the board and suddenly wind up with two kings (unless we have noise, more on that later).\n",
        "\n",
        "**Exercise to the reader**: How many basis states are possible to include in a superposition if we allow the player to make as many normal/split moves as they want? How many superpositions are possible?\n",
        "\n",
        "**Summary**\n",
        "\n",
        "Since the space of possible quantum chess positions is *much* smaller than the space of possible quantum states, it is very tractable to simulate quantum chess if we have a custom simulator tuned to consider only relevant states.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PMKj8n_Rk_uB"
      },
      "source": [
        "## Quantum Chess in Cirq\n",
        "\n",
        "Next, let's define each of these moves in cirq.  We will define a function for each of three possible moves we are considering.  Each of these will use make use of a python structure called [generators](https://wiki.python.org/moin/Generators) which allows us to 'yield' one or more operations.  This will allow us to use these functions very flexibly while we construct circuits.\n",
        "\n",
        "In addition, we will define a function for placing a piece on the board.  Cirq simulators initialize into the zero state (an empty board), so we will use an 'X' gate to turn on a qubit and place a piece on the board."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "WXr_a4xri01v"
      },
      "source": [
        "def normal_move(s: cirq.Qid, t: cirq.Qid):\n",
        "    \"\"\" A normal move in quantum chess.\n",
        "\n",
        "    This function takes two qubits and returns a generator\n",
        "    that performs a normal move that moves a piece from the\n",
        "    source square to the target square.\n",
        "\n",
        "    Args:\n",
        "        s: source qubit (square where piece starts)\n",
        "        t: target qubit (square to move piece to)\n",
        "    \"\"\"\n",
        "    yield cirq.ISWAP(s,t)\n",
        "\n",
        "def split_move(s: cirq.Qid, t1: cirq.Qid, t2: cirq.Qid):\n",
        "    \"\"\" A Split move in quantum chess.\n",
        "\n",
        "    This function takes three qubits and returns a generator\n",
        "    that performs a split move from the source qubit to the\n",
        "    two target qubits.\n",
        "\n",
        "    Args:\n",
        "        s: source qubit (square where piece starts)\n",
        "        t1: target qubit (first square to move piece to)\n",
        "        t2: target qubit (second square to move piece to)\n",
        "    \"\"\"\n",
        "    yield cirq.ISWAP(s,t1)**0.5\n",
        "    yield cirq.ISWAP(s,t2)\n",
        "\n",
        "\n",
        "def slide_move(s: cirq.Qid, t: cirq.Qid, p: cirq.Qid):\n",
        "    \"\"\"A Slide move in quantum chess.\n",
        "\n",
        "    This function takes three qubits and returns a generator\n",
        "    that performs a slide move.  This will move a piece\n",
        "    from the source to the target controlled by the path qubit.\n",
        "    The move will only occur if the path qubit is turned on\n",
        "    (i.e. path qubit should be one if the path is unblocked).\n",
        "\n",
        "    Args:\n",
        "        s: source qubit (square where piece starts)\n",
        "        t: target qubit (square to move piece to)\n",
        "        p: path qubit that determines whether move should occur\n",
        "    \"\"\"\n",
        "    yield cirq.ISWAP(s,t).controlled_by(p)\n",
        "\n",
        "def place_piece(s: cirq.Qid):\n",
        "    \"\"\"Place a piece on the board.\n",
        "\n",
        "    This is not actually a move.  However, since qubits in Cirq\n",
        "    default to starting in the |0> state, we will need to activate\n",
        "    the qubit by applying an X gate to initialize the position.\n",
        "    \"\"\"\n",
        "    yield cirq.X(s)"
      ],
      "execution_count": 100,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mILaTWyGnqoe"
      },
      "source": [
        "Now that the moves are defined as gates in Cirq, let's now define the qubits.  Since we haven't figured out how we will represent this on the hardware, we will use Cirq's concept of `NamedQubit` in order to define the squares as logical qubits without defining a device topology.  This may feel unusual to some, but it can be compared to \"textbook\" circuits that have lines for abstract qubits that are unnamed or have simple symbolic names.  We will first try to define our algorithm in the abstract case, then move towards a physical representation at the end of this colab."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "nTC58KTmoCAq"
      },
      "source": [
        "a1 = cirq.NamedQubit('a1')\n",
        "a2 = cirq.NamedQubit('a2')\n",
        "a3 = cirq.NamedQubit('a3')\n",
        "b1 = cirq.NamedQubit('b1')\n",
        "b2 = cirq.NamedQubit('b2')\n",
        "b3 = cirq.NamedQubit('b3')\n",
        "c1 = cirq.NamedQubit('c1')\n",
        "c2 = cirq.NamedQubit('c2')\n",
        "c3 = cirq.NamedQubit('c3')\n",
        "\n",
        "all_squares = [a1, a2, a3, b1, b2, b3, c1, c2, c3]"
      ],
      "execution_count": 101,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nIWXBkTJoLjp"
      },
      "source": [
        "Now that we have a 3x3 'board' of qubits, let's try to perform some moves.\n",
        "\n",
        "Let's try to create the circuit mentioned in our simulator example that places a king on the 'a1' square, then splits to 'b1' and 'b2', then further splits to 'c1' and 'c2' and then to 'b3' and 'c3'."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "GZILs0lQpFOE",
        "outputId": "3c4f305a-d627-4429-a565-174083cab0eb",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "king_moves = cirq.Circuit(\n",
        "    place_piece(a1),\n",
        "    split_move(a1, b1, b2),\n",
        "    split_move(b1, c1, c2),\n",
        "    split_move(b2, b3, c3),\n",
        ")\n",
        "\n",
        "# Let's print out the circuit to see what it does\n",
        "print(king_moves)\n",
        "\n",
        "# Let's also simulate it using cirq's built-in simulator\n",
        "sim = cirq.Simulator()\n",
        "sim.simulate(king_moves)"
      ],
      "execution_count": 102,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "                       ┌──────────────┐   ┌──────────────┐\n",
            "a1: ───X───iSwap────────iSwap────────────────────────────────────────\n",
            "           │            │\n",
            "b1: ───────iSwap^0.5────┼────iSwap─────────iSwap─────────────────────\n",
            "                        │    │             │\n",
            "b2: ────────────────────iSwap┼─────────────┼────iSwap────────iSwap───\n",
            "                             │             │    │            │\n",
            "b3: ─────────────────────────┼─────────────┼────iSwap^0.5────┼───────\n",
            "                             │             │                 │\n",
            "c1: ─────────────────────────iSwap^0.5─────┼─────────────────┼───────\n",
            "                                           │                 │\n",
            "c2: ───────────────────────────────────────iSwap─────────────┼───────\n",
            "                                                             │\n",
            "c3: ─────────────────────────────────────────────────────────iSwap───\n",
            "                       └──────────────┘   └──────────────┘\n"
          ],
          "name": "stdout"
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "measurements: (no measurements)\n",
              "output vector: -0.5|0000001⟩ - 0.5|0000010⟩ - 0.5|0000100⟩ - 0.5|0001000⟩"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 102
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xGyfSZsarI2f"
      },
      "source": [
        "Fantastic!  We can clearly see that the result from the simulator shows a superposition of 4 states!  So far, so good.  \n",
        "\n",
        "Let's try a slightly more complicated example involving two pieces and an exclusion move that forces a measurement.  \n",
        "\n",
        "Let's start with a king on 'a1' and a queen on 'a3'.  We will split the king onto 'b1' and 'b2' as before.  Next, we will split move the king on 'b1' to 'c1' and 'c2'.  Lastly, we will try to move the queen from 'a3' to 'b2'.\n",
        "\n",
        "![Queen trying to move into a king superposition](./images/qc_blocked_king.png)\n",
        "\n",
        "This will trigger a condition known as \"double occupancy\".  We are not allowed to have two pieces of different types in the same square.  If the king is in 'b2', the queen cannot move there. If the king is not in 'b2', then the move is legal. Thus, we will need to do a measurement.  Let's see how that works.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lpZGhXchr3xf",
        "outputId": "bd2feb6a-b29f-4cf0-c658-7dc106b3ddee",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "exclusion_moves = cirq.Circuit(\n",
        "    place_piece(a1),\n",
        "    place_piece(a3),\n",
        "    split_move(a1, b1, b2),\n",
        "    split_move(b1, c1, c2),\n",
        ")\n",
        "exclusion_move_circuit = exclusion_moves + cirq.measure(b2)\n",
        "\n",
        "\n",
        "# Let's print out the circuit to see what it does\n",
        "print('Exclusion move circuit:')\n",
        "print(exclusion_move_circuit)\n",
        "\n",
        "# This time, we have a measurement in the circuit.\n",
        "# Let's simulate it several times to see what happens.\n",
        "sim = cirq.Simulator()\n",
        "print('Measurement Results:')\n",
        "for t in range(8):\n",
        "    print(f'--- Outcome #{t} ---')\n",
        "    print(sim.simulate(exclusion_move_circuit))"
      ],
      "execution_count": 103,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Exclusion move circuit:\n",
            "                       ┌──────────────┐   ┌──────┐\n",
            "a1: ───X───iSwap────────iSwap────────────────────────\n",
            "           │            │\n",
            "a3: ───X───┼────────────┼────────────────────────────\n",
            "           │            │\n",
            "b1: ───────iSwap^0.5────┼────iSwap─────────iSwap─────\n",
            "                        │    │             │\n",
            "b2: ────────────────────iSwap┼─────────────┼────M────\n",
            "                             │             │\n",
            "c1: ─────────────────────────iSwap^0.5─────┼─────────\n",
            "                                           │\n",
            "c2: ───────────────────────────────────────iSwap─────\n",
            "                       └──────────────┘   └──────┘\n",
            "Measurement Results:\n",
            "--- Outcome #0 ---\n",
            "measurements: b2=0\n",
            "output vector: -0.707|010001⟩ - 0.707|010010⟩\n",
            "--- Outcome #1 ---\n",
            "measurements: b2=1\n",
            "output vector: 1j|010100⟩\n",
            "--- Outcome #2 ---\n",
            "measurements: b2=1\n",
            "output vector: 1j|010100⟩\n",
            "--- Outcome #3 ---\n",
            "measurements: b2=0\n",
            "output vector: -0.707|010001⟩ - 0.707|010010⟩\n",
            "--- Outcome #4 ---\n",
            "measurements: b2=0\n",
            "output vector: -0.707|010001⟩ - 0.707|010010⟩\n",
            "--- Outcome #5 ---\n",
            "measurements: b2=1\n",
            "output vector: 1j|010100⟩\n",
            "--- Outcome #6 ---\n",
            "measurements: b2=1\n",
            "output vector: 1j|010100⟩\n",
            "--- Outcome #7 ---\n",
            "measurements: b2=1\n",
            "output vector: 1j|010100⟩\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gmzaVbLeumP8"
      },
      "source": [
        "In this configuration, you should see two different results.  If we measured the king to be at 'b2', then the position is resolved to a single basis state, equivalent to a classical position (the king is at 'b2' and the queen is at 'c3').\n",
        "\n",
        "If the 'b2' square is measured to be empty, then the board is still in a state of superposition.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FsRPwEZAv2cM"
      },
      "source": [
        "## Handling Partial Measurement\n",
        "\n",
        "So far, we have been simulating this using `cirq.simulate()` which shows us the waveform of the system and its internal state.  In a quantum device, we do not have this information.  All we have is the measurement data that we get out of the device.  Let's try both of these circuits again with the simulator, but denying ourselves access to the underlying wave function, solely using measurement results. \n",
        "\n",
        "First, we will need to add measurements to our previous circuits so that we can access statistical data.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gKojX1NNw04r",
        "outputId": "8ed65122-846f-4906-d642-13549865bc01",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "# Define a measurement operation that measures all the squares\n",
        "measure_all_squares = cirq.measure(*all_squares, key='all')\n",
        "\n",
        "# Measure all squares at the end of the circuit\n",
        "king_moves_measured = king_moves + measure_all_squares\n",
        "exclusion_move_measured = exclusion_moves + measure_all_squares\n",
        "\n",
        "print('Split moving the king:')\n",
        "print(king_moves_measured)\n",
        "results = sim.run(king_moves_measured, repetitions=1)\n",
        "print(results)\n",
        "\n",
        "print('Attempting an exclusion move:')\n",
        "results = sim.run(exclusion_move_measured, repetitions=1)\n",
        "print(results)\n"
      ],
      "execution_count": 104,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Split moving the king:\n",
            "                       ┌──────────────┐   ┌──────────────┐\n",
            "a1: ───X───iSwap────────iSwap────────────────────────────────────────M('all')───\n",
            "           │            │                                            │\n",
            "a2: ───────┼────────────┼────────────────────────────────────────────M──────────\n",
            "           │            │                                            │\n",
            "a3: ───────┼────────────┼────────────────────────────────────────────M──────────\n",
            "           │            │                                            │\n",
            "b1: ───────iSwap^0.5────┼────iSwap─────────iSwap─────────────────────M──────────\n",
            "                        │    │             │                         │\n",
            "b2: ────────────────────iSwap┼─────────────┼────iSwap────────iSwap───M──────────\n",
            "                             │             │    │            │       │\n",
            "b3: ─────────────────────────┼─────────────┼────iSwap^0.5────┼───────M──────────\n",
            "                             │             │                 │       │\n",
            "c1: ─────────────────────────iSwap^0.5─────┼─────────────────┼───────M──────────\n",
            "                                           │                 │       │\n",
            "c2: ───────────────────────────────────────iSwap─────────────┼───────M──────────\n",
            "                                                             │       │\n",
            "c3: ─────────────────────────────────────────────────────────iSwap───M──────────\n",
            "                       └──────────────┘   └──────────────┘\n",
            "all=0, 0, 0, 0, 0, 1, 0, 0, 0\n",
            "Attempting an exclusion move:\n",
            "all=0, 0, 1, 0, 0, 0, 1, 0, 0\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Rzx777ufycSV"
      },
      "source": [
        "You'll notice that, if you run the above block multiple times, you will get different results.\n",
        "\n",
        "We will need a way to compile these into a statistical measure.  For this, we will need to increase the number of repetitions, and then combine them into a histogram.  Let's write a simple function to aggregate the results from the simulator (which are returned in a numpy array) into a more convenient form for us."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "zHMU6BBh15wn",
        "outputId": "98e3a6b1-339b-449e-e8f3-42a01c753935",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "def histogram_of_squares(results):\n",
        "    \"\"\"Creates a histogram of measurement results per square.\n",
        "\n",
        "    Returns:\n",
        "        Dict[str, int] where the key is the name of the square and the\n",
        "        value is the number of times the square was measured in the one state.\n",
        "    \"\"\"\n",
        "    sampling_frequency = {}\n",
        "    for idx, sq in enumerate(all_squares):\n",
        "        sampling_frequency[str(sq)]=results.measurements['all'][:, idx].sum()\n",
        "    return sampling_frequency\n",
        "\n",
        "# Let's test out this histogram on the two circuits we've examined so far:\n",
        "\n",
        "print('Split moving the king:')\n",
        "split_results = sim.run(king_moves_measured, repetitions=1000)\n",
        "print(histogram_of_squares(split_results))\n",
        "\n",
        "print('Attempting an exclusion move:')\n",
        "exclusion_results = sim.run(exclusion_move_measured, repetitions=1000)\n",
        "print(histogram_of_squares(exclusion_results))"
      ],
      "execution_count": 105,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Split moving the king:\n",
            "{'a1': 0, 'a2': 0, 'a3': 0, 'b1': 0, 'b2': 0, 'b3': 257, 'c1': 255, 'c2': 250, 'c3': 238}\n",
            "Attempting an exclusion move:\n",
            "{'a1': 0, 'a2': 0, 'a3': 1000, 'b1': 0, 'b2': 515, 'b3': 0, 'c1': 221, 'c2': 264, 'c3': 0}\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YqYaHpwCPjZF"
      },
      "source": [
        "We can now see the frequencies of different possibilities.  For our first situation, we can see the king has four possibilities with approximately the same amount of occurrences.  Due to statistical variations, the exact number of occurrences in each of the four squares is not exactly the same.\n",
        "\n",
        "\n",
        "Our second exclusion move example illustrates the king's possible position on the three different squares, but we have not yet figured out how to implement the queen's exclusion and measurement with the king.\n",
        "\n",
        "How are we going to do that?\n",
        "\n",
        "First, we need to pick a sample that will become our official \"measurement\" for the board.  We will freeze the seed for the random number generator so that everyone running this colab gets the same measurement and measure the square we care about (b2).\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "_qOYyjdzQcqU",
        "outputId": "7f00f5a2-9348-40dc-e352-9c9850c24f74",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "exclusion_move_measure_b2 = exclusion_moves + cirq.measure(b2)\n",
        "\n",
        "this_sim = cirq.Simulator(seed=1234)\n",
        "measurement_for_move = this_sim.run(exclusion_move_measure_b2, repetitions=1)\n",
        "print(measurement_for_move)"
      ],
      "execution_count": 106,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "b2=0\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YG-k5ukwSFev"
      },
      "source": [
        "When we measure the square 'b2', it is empty.  (The above should consistently print out 'b2=0'.  If it doesn't, you can change your seed so it does).  Thus, we can now move the queen.\n",
        "\n",
        "Ok, we are now ready to make the next move.  How do we figure out the statistics of the board and be able to compute the (quantum) state of the board so that we can continue the game?\n",
        "\n",
        "\n",
        "Let's try to move the queen and see what happens:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "3p4-alb-SzOX",
        "outputId": "37ae8ad5-c5f0-4c18-8068-446303d16217",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "# Calculate the state of the board after moving the queen\n",
        "after_exclusion_move = cirq.Circuit(\n",
        "    place_piece(a1),\n",
        "    place_piece(a3),\n",
        "    split_move(a1, b1, b2),\n",
        "    split_move(b1, c1, c2),\n",
        "    normal_move(a3, b2),\n",
        ") + measure_all_squares\n",
        "\n",
        "# Compute statistics for the pieces.\n",
        "after_results = this_sim.run(after_exclusion_move, repetitions=1000)\n",
        "print(histogram_of_squares(after_results))\n"
      ],
      "execution_count": 107,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "{'a1': 0, 'a2': 0, 'a3': 520, 'b1': 0, 'b2': 1000, 'b3': 0, 'c1': 232, 'c2': 248, 'c3': 0}\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "O9gcnhWqTYkO"
      },
      "source": [
        "Uh oh.  This is not correct.  The queen now has 100% probability of being on 'b2', but there is now a king at 'a3' with approximately 50% probability.\n",
        "\n",
        "The problem is that we are including both the possibility that the king was at 'b2' as well as the possibility that it was empty.  Instead of initializing the king to 'a1', we could initialize the king to 'b1' and just do one split move from 'b1' to 'c1' and 'c2' instead of performing all operations since the beginning of the game.\n",
        "\n",
        "This has two issues.  First is that we are cheating somewhat by using the simplicity of this toy example to only include paths that are possible.  In a more complicated game, with pieces and merges happening, it may be a lot more difficult to simplify the circuit in a way that replicates the results of a measurement.  The second problem is that we have discarded information about the relative phases of the pieces.  For instance, the different squares could have picked up phases of $i$, and we would not be able to tell by just looking at the measurement results.  We may be destroying this information by simplifying the circuit.\n",
        "\n",
        "**Exercise to the reader**:  Is the phase actually the same or different if we compute the shorter circuit?\n",
        "\n",
        "So then, how do we handle this?"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "S5pmjHhPWRqy"
      },
      "source": [
        "## Post-selection\n",
        "\n",
        "One way of resolving this is to use the method of \"post-selection\".  Both simulators and real hardware have the ability to repeat an experiment many times.  We can use this ability to pick the samples that match our expectations of the results.  \n",
        "\n",
        "In the example above, we have two independent possibilities for the measurement of the king.  Half of results will have 'm0' (the king was on the square preventing the queen move) and half will have 'm1' result (the king was not there and the queen move was possible).  In our game, we know that 'm0' is what happened, so we can run the simulation multiple times and only take the results that are consistent with 'm0'.\n",
        "\n",
        "This procedure is only needed since we need to run the simulation from the beginning of the board each time.  If we could \"save\" the state vector from the last move, we would not need to do this.  We could just apply the next move on the last state vector.  While this is possible in a classical simulator, quantum states in a real device only stay coherent for mere microseconds and won't wait around while we ponder our next quantum chess move.\n",
        "\n",
        "A quantum algorithm that uses results of measurements to affect later steps is called a \"feed-forward\".  We are going to use post-selection to transform the current feed-forward algorithm of quantum chess into an algorithm that has terminal measurements only.\n",
        "\n",
        "We will transform our first algorithm from:\n",
        "\n",
        "*  Make some non-measurement moves.\n",
        "*  Make a move that requires measurement and gets an outcome of 'm0'\n",
        "*  Make a second set of non-measurement moves based on this outcome.\n",
        "\n",
        "Into the following new algorithm:\n",
        "\n",
        "*  Make some non-measurement moves.\n",
        "*  Make the exclusion move but don't measure yet.\n",
        "*  Make the second set of moves.\n",
        "*  Measure the relevant qubits.  Discard results that do not match our expected result of 'm0'\n",
        "\n",
        "Note that we have to be careful when we do this.  First, we have to track the qubits to perform the correct measurement.  In our example above, the queen moved to the 'b2' square, regardless of whether the king was there.  Executing that move swapped the qubits of 'b2' and 'a3'.  So, when we measure the king's position at the end of the circuit, we need to measure its new position within the 'a3' qubit.\n",
        "\n",
        "Second, we need to ensure that the two outcomes are truly independent.  If further moves begin interacting with our 'a3' square that holds the position of the king, then we may get incorrect results.  To do this correctly, we may want to swap the king's state into an ancillary qubit so that it doesn't interact with further moves.  This is left as an exercise to the reader.\n",
        "\n",
        "The following code shows how we might do this for the example circuit:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "K4NVLx16XKzh",
        "outputId": "2cb4ef83-09a7-45bd-f7db-0e9fdbf98078",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "# Perform all the moves, including the exclusion move.\n",
        "# Afterwards, measure all qubits.\n",
        "after_exclusion_move = cirq.Circuit(\n",
        "    place_piece(a1),\n",
        "    place_piece(a3),\n",
        "    split_move(a1, b1, b2),\n",
        "    split_move(b1, c1, c2),\n",
        "    normal_move(a3, b2),\n",
        ") + measure_all_squares\n",
        "\n",
        "# Define a function to post select on the result.\n",
        "def histogram_post_select(results, square_idx, value):\n",
        "    \"\"\"Return a histogram of measurement results with post-selection.\n",
        "\n",
        "    This will return a dictionary of str to int, with the key being\n",
        "    the name of the square and the value being the number of times the\n",
        "    square was measured as one. These results will exclude any results\n",
        "    where the square represented by `square_idx` were not equal to `value`.\n",
        "\n",
        "    Args:\n",
        "        results: TrialResults returned by a sampler.\n",
        "        square_idx: integer index of the measured qubit to post-select on.\n",
        "        value: whether the qubit post-selected should be one or zero.\n",
        "    \"\"\"\n",
        "    sampling_frequency = {}\n",
        "    all_results = results.measurements['all']\n",
        "    post_selected_results = all_results[all_results[:,square_idx]==value]\n",
        "    for idx, sq in enumerate(all_squares):\n",
        "        sampling_frequency[str(sq)]=post_selected_results[:, idx].sum()\n",
        "    return sampling_frequency\n",
        "\n",
        "# Compute statistics for the pieces.\n",
        "after_results = this_sim.run(after_exclusion_move, repetitions=1000)\n",
        "\n",
        "# Find the index of 'a3' (it should be at index 2)\n",
        "post_select_idx = all_squares.index(cirq.NamedQubit('a3'))\n",
        "\n",
        "# Print out the post-selected histogram\n",
        "print(histogram_post_select(after_results, post_select_idx, 0))"
      ],
      "execution_count": 108,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "{'a1': 0, 'a2': 0, 'a3': 0, 'b1': 0, 'b2': 516, 'b3': 0, 'c1': 227, 'c2': 289, 'c3': 0}\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zb4U6KsLYmKt"
      },
      "source": [
        "We now have about half the number of results, but they only include results with the relevant measurement outcomes.  We now have replicated the correct state of the board after the exclusion board.  \n",
        "\n",
        "To show that we can use this state to continue the quantum chess game, let's make a final move from the king from c2 to c3.  This represents the board state with king on 'a1', queen on 'a3' after the moves \n",
        "*Ka1^b1b2, Kb1^c1c2, Qa3b2.m1, Kc2c3*:\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "yDK44EOzZeZL",
        "outputId": "fbf338c7-2d0a-48a2-9295-ee959b7c729f",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "after_exclusion_without_measurement = cirq.Circuit(\n",
        "    place_piece(a1),\n",
        "    place_piece(a3),\n",
        "    split_move(a1, b1, b2),\n",
        "    split_move(b1, c1, c2),\n",
        "    normal_move(a3, b2),\n",
        "    normal_move(c2, c3),\n",
        ")\n",
        "after_exclusion_move = after_exclusion_without_measurement + measure_all_squares\n",
        "\n",
        "after_results = this_sim.run(after_exclusion_move, repetitions=1000)\n",
        "post_select_idx = all_squares.index(cirq.NamedQubit('a3'))\n",
        "print(histogram_post_select(after_results, post_select_idx, 0))"
      ],
      "execution_count": 109,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "{'a1': 0, 'a2': 0, 'a3': 0, 'b1': 0, 'b2': 480, 'b3': 0, 'c1': 236, 'c2': 0, 'c3': 244}\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NIORVBizempc"
      },
      "source": [
        "We can now see that the measurements that were on 'c2' have now moved to 'c3'.  This illustrates how we can continue a quantum chess move sequence that contains a partial measurement part-way through the sequence, even on a device that only supports final measurement!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rHCxyi3QdXP4"
      },
      "source": [
        "## Noise\n",
        "\n",
        "So far, we have dealt with a simulator that is completely noiseless.  Even so, we have already seen statistical fluctuations that affect our probabilities.  Real NISQ devices will have a lot of noise that will affect calculations in every way possible.\n",
        "\n",
        "There are many components to noise.  Some possible (overlapping) sources of noise include:\n",
        "\n",
        "*   **T1 Decay / relaxation**:  Qubits in the excited state $\\vert 1\\rangle$ could lose energy and fall into the ground state $\\vert 0\\rangle$.  This is typically qualified by a metric called T1 that specifies the rate of exponential decay (similar to a \"half-life\" of radioactive decay).\n",
        "*   **Dephasing error**:  Qubits could be \"spinning\" in relation to each other.  For instance, a qubit in $\\frac{1}{\\sqrt{2}} (\\vert0\\rangle + \\vert 1\\rangle)$ could become $\\frac{1}{\\sqrt{2}} (\\vert0\\rangle + i\\vert 1\\rangle)$.  This is sometimes simplified to a measure called T2 or T2*.  However, since dephasing errors can \"spin\" at many different rates and directions, a full noise spectrum is needed to fully characterize these types of errors.\n",
        "*   **Readout/measurement error**: If we accidentally detect a $\\vert 0\\rangle$ as a $\\vert 1\\rangle$ or vice versa when performing a measurement, this is often classified as a readout error. \n",
        "*   **Control/Coherent error**: The device can drift out of calibration or can be too difficult to control effectively.  If every time that we do a $\\text{iSWAP}$ gate, we consistently do a $\\text{iSWAP}^{0.98}$, this is a coherent error.\n",
        "*   **Cross talk**: Effects that involve specific pairs of (usually nearby) qubits could occur that can create correlations or entanglements.  These effects are often more difficult to model and fix.\n",
        "\n",
        "Luckily, we don't need an actual hardware device to simulate (some of these) noisy effects.  We can simulate them using cirq's simulator.\n",
        "\n",
        "Let's run the simulator with the moves Ka1^b1b2, Kb1^c1c2, Kb2^b3c3 that we were examining before, but this time using one of cirq's noise models called a [depolarizing channel](https://en.wikipedia.org/wiki/Quantum_depolarizing_channel) that randomly scrambles a qubit with a set probability.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "smtHhiffhboj",
        "outputId": "45834aee-1fc6-45d4-c870-ec817b7930dd",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "import cirq.contrib.noise_models as ccn\n",
        "noise_model = ccn.DepolarizingNoiseModel(depol_prob=0.01)\n",
        "noisy=cirq.DensityMatrixSimulator(noise=noise_model)\n",
        "\n",
        "king_moves_measured = cirq.Circuit(\n",
        "    place_piece(a1),\n",
        "    split_move(a1, b1, b2),\n",
        "    split_move(b1, c1, c2),\n",
        "    split_move(b2, b3, c3),\n",
        ") + measure_all_squares\n",
        "\n",
        "print(histogram_of_squares(noisy.run(king_moves_measured, repetitions=1000)))"
      ],
      "execution_count": 110,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "{'a1': 40, 'a2': 41, 'a3': 34, 'b1': 27, 'b2': 32, 'b3': 247, 'c1': 275, 'c2': 262, 'c3': 272}\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ajY6TngojCer"
      },
      "source": [
        "These results look a lot messier than what we were looking at before.  First, all 9 squares have some probability of the king being there, even though there is no possibility that the king can be there.  That's a problem.\n",
        "\n",
        "Also, the results no longer add up to 1000.  Uh oh.  How is that even possible?  Have we made a mistake?\n",
        "\n",
        "If noise flips some of the qubits to |1>, we can now measure a state that records the king in two places.  For instance `|100 000 001>` is a state that could be achieved with a single incorrect bit flip and represents the board state with two kings: one on 'a1' and one on 'c3'.  This will give us two entries in the histogram for a single repetition of the circuit, causing the total to exceed 1000.\n",
        "\n",
        "We know that there is no way to create pieces in chess, so some of these results are nonsensical.\n",
        "\n",
        "One way to do error mitigation is to detect these nonsensical events and remove them.  Let's recode this to use \"post-selection\" to exclude measurements that have more than one king (or that have zero kings), which we know are impossible positions to reach in this situation."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-RfqhdwnlfoU",
        "outputId": "60fe9d4a-695e-4f4f-fb41-bcb627cd43dc",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "def remove_multi_kings(results):\n",
        "    \"\"\"Removes samples from a set of results that do not have one measurement.\n",
        "\n",
        "    Returns a histogram dictionary as defined above that only has results that\n",
        "    have one square with a measurement outcome of one and all other squares have\n",
        "    measurement outcomes of zero.  Results that do not fit this pattern are\n",
        "    discarded.\n",
        "    \"\"\"\n",
        "    sampling_frequency = {}\n",
        "    all_results = results.measurements['all']\n",
        "    # Select only rows where the row sums to one.\n",
        "    post_selected_results = all_results[all_results[:,:].sum(axis=1)==1]\n",
        "    for idx, sq in enumerate(all_squares):\n",
        "        sampling_frequency[str(sq)]=post_selected_results[:, idx].sum()\n",
        "    return sampling_frequency\n",
        "\n",
        "results = noisy.run(king_moves_measured, repetitions=1000)\n",
        "print(remove_multi_kings(results))"
      ],
      "execution_count": 111,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "{'a1': 4, 'a2': 2, 'a3': 0, 'b1': 2, 'b2': 0, 'b3': 187, 'c1': 163, 'c2': 184, 'c3': 198}\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hAGw7o18mnHr"
      },
      "source": [
        "This data is much better!  We have not eliminated all the noise, but, by taking into account the constraints and invariants of the problem we are trying to solve, we have eliminated much of the noise!\n",
        "\n",
        "Next, let's look at another source of noise."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jaU-j-fLoRjv"
      },
      "source": [
        "### Coherent noise\n",
        "\n",
        "Let's say that our device consistently performs incorrect operations, but that we do not know the exact nature of these errors.  Is there a way to correct for these types of problems?\n",
        "\n",
        "Let's suppose that, instead of doing an iSWAP, our device does part of an iSWAP, but that amount differs from day to day and we don't know what the percentage of an iswap is going to be.  One day it could be 50% of an iSWAP, and the next day it could be 80% of an iSWAP.  We don't know what that percentage is, but we know that it will stay fairly stable throughout our calculation.\n",
        "\n",
        "How would that affect our results?\n",
        "Let's define a function called \"lazy_move\" that represents this partial iSWAP.  Then, let's march the king from a1 to a2 to a3 to b3 to c3 using this under-rotated iSWAP and see what happens."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "xaPWtoYNozrg",
        "outputId": "a5ba09dd-4c2f-48a0-df51-575e4354e849",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "import random\n",
        "\n",
        "# Define our secret under-rotation parameter once across multiple executions.\n",
        "try:\n",
        "    _secret_lazy_value\n",
        "except:\n",
        "    _secret_lazy_value = (random.random() + 2.0) / 4.0\n",
        "\n",
        "def lazy_move(source, target):\n",
        "    return cirq.ISWAP(source, target) ** _secret_lazy_value\n",
        "\n",
        "king_maybe_moves = cirq.Circuit(\n",
        "    place_piece(a1),\n",
        "    lazy_move(a1,a2),\n",
        "    lazy_move(a2,a3),\n",
        "    lazy_move(a3,b3),\n",
        "    lazy_move(b3,c3)\n",
        ") + measure_all_squares\n",
        "\n",
        "print(histogram_of_squares(sim.run(king_maybe_moves, repetitions=1000)))\n"
      ],
      "execution_count": 112,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "{'a1': 200, 'a2': 169, 'a3': 120, 'b1': 0, 'b2': 0, 'b3': 98, 'c1': 0, 'c2': 0, 'c3': 413}\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7Yp9g3iqqdFb"
      },
      "source": [
        "As we run this circuit, we see that the king leaks across the path it takes and only some of the probability makes it to the final destination.  However, this probability remains roughly the same across multiple invocations. \n",
        "\n",
        "Can we correct or \"calibrate\" this broken gate so that it is fixed for our use case?\n",
        "\n",
        "Let's suppose our device supports a rotation angle for our iSWAP gate.  Can we over-rotate the gate on purpose to counter-act the device's error?\n",
        "\n",
        "Let's try it."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "cYMU1hMQriNr",
        "outputId": "0708005a-a776-4dc1-e412-062e546bd64c",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "over_rotation_amount = 1.46\n",
        "\n",
        "king_probably_moves = cirq.Circuit(\n",
        "    place_piece(a1),\n",
        "    lazy_move(a1,a2) ** over_rotation_amount,\n",
        "    lazy_move(a2,a3) ** over_rotation_amount,\n",
        "    lazy_move(a3,b3) ** over_rotation_amount,\n",
        "    lazy_move(b3,c3) ** over_rotation_amount\n",
        ") + measure_all_squares\n",
        "\n",
        "print(histogram_of_squares(sim.run(king_probably_moves, repetitions=1000)))"
      ],
      "execution_count": 113,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "{'a1': 5, 'a2': 2, 'a3': 4, 'b1': 0, 'b2': 0, 'b3': 4, 'c1': 0, 'c2': 0, 'c3': 985}\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SUplJ5LPr246"
      },
      "source": [
        "This looks better, but still not perfect.\n",
        "\n",
        "In a real example, you may need to tune the operations slightly automatically\n",
        "to correct for coherent error.  This is vastly simplified example of what is being performed when a quantum device is being calibrated.  The device operator is attempting to perfect the physical operations (such as microwave pulses) to match the intended logical operation (such as iSWAP).   Even as a user of a calibrated device, sometimes procedures like this are needed since the operations may not be uniform across the entire processor, and they may drift over time.\n",
        "\n",
        "Let's write a routine to try to optimize our\n",
        "over rotation constant in order to automatically tune out the under-rotation.  In this example, we will do a linear sweep using a parameter value to find the best value.  In a real example, you may want to use an gradient optimizer such as scipy.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "UM-aBkaQSpcH",
        "outputId": "7fa3a72e-8fcc-4a02-8aca-b9c0bb14a124",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "import sympy\n",
        "\n",
        "# Our calibration will be to perform one swap\n",
        "# We will then measure how many times the king actually gets there.\n",
        "king_calibration = cirq.Circuit(\n",
        "    place_piece(a1),\n",
        "    lazy_move(a1,a2) ** sympy.Symbol('r'),\n",
        "    cirq.measure(a1, a2, key='all') )\n",
        "\n",
        "# We will try all rotation values from 1.0 to 3.0 at intervals of 0.01\n",
        "rotation_parameter = cirq.Linspace('r', 1.0, 3.0, 200)\n",
        "results = sim.run_sweep(king_calibration,\n",
        "                             params=rotation_parameter,\n",
        "                             repetitions=1000)\n",
        "\n",
        "# Then we will keep track of the best value we found so far.\n",
        "best_over_rotation = 1.0\n",
        "most_correct_swaps = 0\n",
        "for result in results:\n",
        "    num_correct_swaps = result.measurements['all'][:,1].sum()\n",
        "    if num_correct_swaps > most_correct_swaps:\n",
        "        most_correct_swaps = num_correct_swaps\n",
        "        best_over_rotation = result.params['r']\n",
        "\n",
        "print(f'Best over rotation value found: {best_over_rotation}')\n",
        "print(f'Implied secret swap value: {1/best_over_rotation}')\n",
        "print(f'Actual secret swap value: {_secret_lazy_value}')"
      ],
      "execution_count": 114,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Best over rotation value found: 1.391959798994975\n",
            "Implied secret swap value: 0.7184115523465703\n",
            "Actual secret swap value: 0.7058894035710013\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kKKza176WcCC"
      },
      "source": [
        "Our calibration found a rotation value that corrects for the under-rotation.\n",
        "\n",
        "**Exercise to the reader**: Is there a way to get closer to the correct result?  Hint: it may cause the simulation to take longer to run."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SEf9BgJEsbwM"
      },
      "source": [
        "There are many other types of noise, but it is inevitable that you will need to think about noise as you develop your own applications and mitigate the error to the largest extent possible if you want your application to be successful."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "73WRRNSPtIqr"
      },
      "source": [
        "## Decomposition\n",
        "\n",
        "Most devices in the NISQ era will only support certain gate types, often referred to as a gate set.\n",
        "\n",
        "Let's suppose that our device only supports one two-qubit gate, the $\\sqrt{\\text{iSWAP}}$ gate `cirq.ISWAP ** 0.5`.\n",
        "\n",
        "How does that affect our quantum chess circuits?\n",
        "\n",
        "Luckily, most of the moves use either $\\sqrt{\\text{iSWAP}}$ gates or $\\text{iSWAP}$ gates (which are merely two $\\sqrt{\\text{iSWAP}}$ gates in a row).\n",
        "\n",
        "However, the slide move (which we have ignored so far), is a $\\text{controlled-iSWAP}$ gate.  How will we perform this on hardware?\n",
        "\n",
        "We will need to transform it into gates we understand.  This is often called \"decomposing\" the gate.\n",
        "\n",
        "First, let's explore some of cirq's capability in this area.  Cirq has some decomposition routines for known gates.  Let's see what happens when we decompose the Hadamard $\\text{H}$ gate and the two-qubit $\\text{CNOT}$ gate.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ijOq1Sx8uh66",
        "outputId": "5f276d98-a1c6-44fa-bfaf-3e1e054fa8f6",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "print('Decomposing H gate')\n",
        "decomposed_h = cirq.decompose_once(cirq.H(a1))\n",
        "print(decomposed_h)\n",
        "print(cirq.Circuit(decomposed_h))\n",
        "print()\n",
        "\n",
        "print('Decomposing CNOT gate')\n",
        "decomposed_cnot = cirq.decompose_once(cirq.CNOT(a1, a2))\n",
        "print(decomposed_cnot)\n",
        "print(cirq.Circuit(decomposed_cnot))\n",
        "print()\n"
      ],
      "execution_count": 115,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Decomposing H gate\n",
            "[(cirq.Y**0.5).on(cirq.NamedQubit('a1')), cirq.XPowGate(exponent=1.0, global_shift=-0.25).on(cirq.NamedQubit('a1'))]\n",
            "a1: ───Y^0.5───X───\n",
            "\n",
            "Decomposing CNOT gate\n",
            "[(cirq.Y**-0.5).on(cirq.NamedQubit('a2')), cirq.CZ(cirq.NamedQubit('a1'), cirq.NamedQubit('a2')), (cirq.Y**0.5).on(cirq.NamedQubit('a2'))]\n",
            "a1: ────────────@───────────\n",
            "                │\n",
            "a2: ───Y^-0.5───@───Y^0.5───\n",
            "\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "I25Uq7puvGRR"
      },
      "source": [
        "cirq decomposes an H into a Y rotation and then a X rotation.  It decomposes a $\\text{CNOT}$ into a $\\text{CZ}$ gate with some single-qubit gates.  Neat, but it doesn't help us get closer to our goal of decomposing to a $\\sqrt{\\text{iSWAP}}$.\n",
        "\n",
        "Let's see what happens when we decompose the $\\text{controlled-iSWAP}$ gate."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "PyG5PFGovfZy",
        "outputId": "9e37a19a-6aa0-4699-a7c3-a43b115e6ed9",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "cirq.decompose_once(cirq.ISWAP(a1,a3).controlled_by(a2))"
      ],
      "execution_count": 116,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[cirq.CNOT(cirq.NamedQubit('a1'), cirq.NamedQubit('a3')).controlled_by(cirq.NamedQubit('a2')),\n",
              " cirq.H(cirq.NamedQubit('a1')).controlled_by(cirq.NamedQubit('a2')),\n",
              " cirq.CNOT(cirq.NamedQubit('a3'), cirq.NamedQubit('a1')).controlled_by(cirq.NamedQubit('a2')),\n",
              " cirq.S(cirq.NamedQubit('a1')).controlled_by(cirq.NamedQubit('a2')),\n",
              " cirq.CNOT(cirq.NamedQubit('a3'), cirq.NamedQubit('a1')).controlled_by(cirq.NamedQubit('a2')),\n",
              " (cirq.S**-1).on(cirq.NamedQubit('a1')).controlled_by(cirq.NamedQubit('a2')),\n",
              " cirq.H(cirq.NamedQubit('a1')).controlled_by(cirq.NamedQubit('a2')),\n",
              " cirq.CNOT(cirq.NamedQubit('a1'), cirq.NamedQubit('a3')).controlled_by(cirq.NamedQubit('a2'))]"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 116
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2RJ3dM41vmKS"
      },
      "source": [
        "Oh, yikes.  cirq is able to handle decomposing this, but it uses the decomposition of iSWAP with the control bit attached to all gates.  The result is an expansion into several three qubit gates and two qubit gates.  While correct, this looks to be going the wrong direction in terms of circuit complexity.\n",
        "\n",
        "We will need a more powerful tool.  Let's use the concept of an optimizer.  This is a cirq tool that can run through a circuit, making changes as it goes along.  It can be used for compiling to a specific gate set, compressing circuits into less space, or other useful transformations.\n",
        "\n",
        "Luckily, one already exists for compiling to $\\sqrt{\\text{iSWAP}}$.  `cirq.google.optimized_for_sycamore`.  Let's first demonstrate this with the CNOT gate:\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "JUgavVIaQ-ld",
        "outputId": "f52e5e24-1d04-4083-fd6c-5890dd101064",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "print(cirq.google.optimized_for_sycamore(cirq.Circuit(cirq.CNOT(a1, a2))))"
      ],
      "execution_count": 117,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "a1: ───PhXZ(a=-0.5,x=0.5,z=0.5)───iSwap────────PhXZ(a=-1,x=1,z=0)───iSwap───────PhXZ(a=0,x=0.5,z=0)────────\n",
            "                                  │                                 │\n",
            "a2: ───PhXZ(a=-1,x=0,z=0.5)───────iSwap^-0.5────────────────────────iSwap^0.5───PhXZ(a=0.5,x=0.5,z=-0.5)───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MONYSOOYRM8Y"
      },
      "source": [
        "Now we can see that, instead of decomposing into a CZ gate, it decomposes the CNOT into $\\sqrt{\\text{iSWAP}}$ gates in addition to some one-qubit phased XZ gates.\n",
        "\n",
        "Let's try it with the more complicated case of a **controlled-iSWAP**:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "6LrBUQ6bwUu2",
        "outputId": "ee0ce06f-ccf2-4de7-e973-63a1e7ed5ccc",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "c_iswap = cirq.Circuit(cirq.ISWAP(a1,a3).controlled_by(a2))\n",
        "try:\n",
        "    cirq.google.optimized_for_sycamore(c_iswap, optimizer_type='sqrt_iswap')\n",
        "except Exception as e:\n",
        "    print('An error occurred while attempting to optimize: ')\n",
        "    print(e)"
      ],
      "execution_count": 118,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "An error occurred while attempting to optimize: \n",
            "Don't know how to work with CY**-0.5(a2, a3). It isn't a native sqrt ISWAP operation, a 1 or 2 qubit gate with a known unitary, or composite.\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sT1OwZiMxDMa"
      },
      "source": [
        "Yuck.  It looks like it gets stuck.  We will need to help it out a bit to get it into a form that it can understand.\n",
        "\n",
        "One common transformation that might help is that a controlled-SWAP (often called a Fredkin gate) does have a known transformation into a Toffoli (another three qubit gate that is a controlled-CNOT) and two CNOT gates.  Let's double-check that."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "CDJe_jNxxVsH",
        "outputId": "105e1b62-c27f-4575-98ba-6f29126f6a77",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "import numpy as np\n",
        "\n",
        "c_swap = cirq.Circuit(cirq.SWAP(a1, a3).controlled_by(a2))\n",
        "c_swap_decomposed = cirq.Circuit(cirq.CNOT(a1, a3), cirq.TOFFOLI(a2, a3, a1), cirq.CNOT(a1, a3))\n",
        "c_swap_unitary = cirq.unitary(c_swap)\n",
        "c_swap_decomposed_unitary = cirq.unitary(c_swap_decomposed)\n",
        "\n",
        "print('Unitary of controlled SWAP')\n",
        "print(c_swap_unitary)\n",
        "print('Unitary of decomposed circuit')\n",
        "print(c_swap_decomposed_unitary)\n",
        "print('Are they equal?')\n",
        "print(np.isclose(c_swap_unitary, c_swap_decomposed_unitary).all())"
      ],
      "execution_count": 119,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Unitary of controlled SWAP\n",
            "[[1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j]]\n",
            "Unitary of decomposed circuit\n",
            "[[1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j]]\n",
            "Are they equal?\n",
            "True\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Fv5bJeFQYaWx"
      },
      "source": [
        "With some leaps of intuition or mathematics, one might try to add an operation to the circuit to rotate the swap slightly to get an **iSWAP**.\n",
        "\n",
        "Let's add a CZ ** 0.5 gate in the middle to try to change this from a **SWAP** to an **iSWAP**.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BLBFZZqfYwsX",
        "outputId": "31e0e345-8230-4d88-f35e-734c1d4f062d",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "import numpy as np\n",
        "\n",
        "c_iswap = cirq.Circuit(cirq.ISWAP(a3, a2).controlled_by(a1))\n",
        "c_iswap_decomposed = cirq.Circuit(cirq.CNOT(a3, a2), cirq.TOFFOLI(a1, a2, a3), cirq.CZ(a1, a2) ** 0.5, cirq.CNOT(a3, a2))\n",
        "c_iswap_unitary = cirq.unitary(c_iswap)\n",
        "c_iswap_decomposed_unitary = cirq.unitary(c_iswap_decomposed)\n",
        "\n",
        "print('Unitary of controlled iSWAP')\n",
        "print(c_iswap_unitary)\n",
        "print('Unitary of decomposed circuit')\n",
        "print(c_iswap_decomposed_unitary)\n",
        "print('Are they equal?')\n",
        "print(np.isclose(c_iswap_unitary, c_iswap_decomposed_unitary).all())"
      ],
      "execution_count": 120,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Unitary of controlled iSWAP\n",
            "[[1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+1.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+1.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j]]\n",
            "Unitary of decomposed circuit\n",
            "[[1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+1.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+1.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j]]\n",
            "Are they equal?\n",
            "True\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lq2zSozot0ay"
      },
      "source": [
        "This is great.  Let's see if we can decompose this circuit using the built-in operations from cirq."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ZghUHMubuKJ1",
        "outputId": "3479b117-27d4-48be-9b19-ad93fe581117",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "decomposed_circuit = cirq.google.optimized_for_sycamore(c_iswap_decomposed, \n",
        "                                                        optimizer_type='sqrt_iswap')\n",
        "print(f'Circuit: {len(decomposed_circuit)} moments')\n",
        "print(decomposed_circuit)"
      ],
      "execution_count": 121,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Circuit: 45 moments\n",
            "a1: ───PhXZ(a=-0.75,x=0.5,z=0.75)─────────────────────────────────────────────────────────────────────────────iSwap────────PhXZ(a=-1,x=1,z=0)───iSwap───────PhXZ(a=-0.5,x=0.5,z=-1)──────────────────────────────────────────────────────────────────────────────────iSwap────────PhXZ(a=-1,x=1,z=0)───iSwap───────PhXZ(a=-0.5,x=0.5,z=-1)─────────────────────────────────────────────────────────────────────────────iSwap────────PhXZ(a=-1,x=1,z=0)───iSwap───────PhXZ(a=-0.5,x=0.5,z=-1)─────────────────────────────────────────────────────────────────────────────iSwap────────PhXZ(a=-1,x=1,z=0)───iSwap───────PhXZ(a=-0.0991,x=0.595,z=0.364)──────────────────────────────────────────────────────────────────────────iSwap────────PhXZ(a=-1,x=0.364,z=0)───iSwap───────PhXZ(a=0,x=0.136,z=0)────────────────────────────────────────────────────────────────────────────\n",
            "                                                                                                              │                                 │                                                                                                                    │                                 │                                                                                                               │                                 │                                                                                                               │                                 │                                                                                                                    │                                     │\n",
            "a2: ───PhXZ(a=-1,x=0,z=0.5)─────────iSwap─────────────────────────────iSwap───────PhXZ(a=0.5,x=0.5,z=0.25)────iSwap^-0.5────────────────────────iSwap^0.5───PhXZ(a=0,x=0.5,z=0.5)─────iSwap────────PhXZ(a=-1,x=1,z=0)───iSwap───────PhXZ(a=-1.11e-16,x=0.5,z=0.25)───iSwap^-0.5────────────────────────iSwap^0.5───PhXZ(a=0,x=0.5,z=0.5)─────iSwap────────PhXZ(a=-1,x=1,z=0)───iSwap───────PhXZ(a=0,x=0.5,z=0.5)───────iSwap^-0.5────────────────────────iSwap^0.5───PhXZ(a=0,x=0.5,z=0.5)─────iSwap────────PhXZ(a=-1,x=1,z=0)───iSwap───────PhXZ(a=0,x=0.5,z=0.5)───────iSwap^-0.5────────────────────────iSwap^0.5───PhXZ(a=0,x=0.5,z=0.5)─────────────iSwap────────PhXZ(a=-1,x=1,z=0)───iSwap───────PhXZ(a=0.5,x=0.25,z=0)───iSwap^-0.5────────────────────────────iSwap^0.5───PhXZ(a=0,x=0.5,z=0.5)───iSwap─────────────────────────────iSwap───────PhXZ(a=0.5,x=0.5,z=-0.5)───\n",
            "                                    │                                 │                                                                                                               │                                 │                                                                                                                    │                                 │                                                                                                               │                                 │                                                                                                                       │                                 │                                                                                                              │                                 │\n",
            "a3: ───PhXZ(a=-0.5,x=0.5,z=0.5)─────iSwap^-0.5───PhXZ(a=-1,x=1,z=0)───iSwap^0.5───PhXZ(a=-0.5,x=0.5,z=0.25)───────────────────────────────────────────────────────────────────────────iSwap^-0.5────────────────────────iSwap^0.5───PhXZ(a=0.5,x=0.5,z=0.25)─────────────────────────────────────────────────────────────────────────────────iSwap^-0.5────────────────────────iSwap^0.5───PhXZ(a=0.5,x=0.5,z=-0.25)───────────────────────────────────────────────────────────────────────────iSwap^-0.5────────────────────────iSwap^0.5───PhXZ(a=0.5,x=0.5,z=-0.25)───────────────────────────────────────────────────────────────────────────────────iSwap^-0.5────────────────────────iSwap^0.5───PhXZ(a=0.5,x=0.5,z=-1)─────────────────────────────────────────────────────────────────────────────iSwap^-0.5───PhXZ(a=-1,x=1,z=0)───iSwap^0.5───PhXZ(a=0,x=0.5,z=0)────────\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "y55SZkTZusOE"
      },
      "source": [
        "So, a bit of good news and a bit of bad news.  We are able to create a circuit that can run on hardware that only supports $\\sqrt{\\text{iSWAP}}$ and single-qubit gates, but the circuit is extremely long (45 moments).\n",
        "\n",
        "More advanced techniques and intuition can lead to better decompositions, but that is out-of-scope of this tutorial.  We'll leave that as a (quite advanced) exercise for the reader."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MDjmEgSL2z82"
      },
      "source": [
        "## Qubit layout\n",
        "\n",
        "So far, we have been dealing with NamedQubits, since they match very logically to the squares of the quantum chess board.  However, this is not how real devices work.  We will need to map these abstract qubits to real qubits on a device.  Let's consider a Google Sycamore device with 54 qubits arranged in a grid layout:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "RthyrJWS3uKA",
        "outputId": "00f0f29a-899f-4970-b880-fefa0494175d",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "print(cirq.google.Sycamore)"
      ],
      "execution_count": 122,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "                                             (0, 5)───(0, 6)\n",
            "                                             │        │\n",
            "                                             │        │\n",
            "                                    (1, 4)───(1, 5)───(1, 6)───(1, 7)\n",
            "                                    │        │        │        │\n",
            "                                    │        │        │        │\n",
            "                           (2, 3)───(2, 4)───(2, 5)───(2, 6)───(2, 7)───(2, 8)\n",
            "                           │        │        │        │        │        │\n",
            "                           │        │        │        │        │        │\n",
            "                  (3, 2)───(3, 3)───(3, 4)───(3, 5)───(3, 6)───(3, 7)───(3, 8)───(3, 9)\n",
            "                  │        │        │        │        │        │        │        │\n",
            "                  │        │        │        │        │        │        │        │\n",
            "         (4, 1)───(4, 2)───(4, 3)───(4, 4)───(4, 5)───(4, 6)───(4, 7)───(4, 8)───(4, 9)\n",
            "         │        │        │        │        │        │        │        │\n",
            "         │        │        │        │        │        │        │        │\n",
            "(5, 0)───(5, 1)───(5, 2)───(5, 3)───(5, 4)───(5, 5)───(5, 6)───(5, 7)───(5, 8)\n",
            "         │        │        │        │        │        │        │\n",
            "         │        │        │        │        │        │        │\n",
            "         (6, 1)───(6, 2)───(6, 3)───(6, 4)───(6, 5)───(6, 6)───(6, 7)\n",
            "                  │        │        │        │        │\n",
            "                  │        │        │        │        │\n",
            "                  (7, 2)───(7, 3)───(7, 4)───(7, 5)───(7, 6)\n",
            "                           │        │        │\n",
            "                           │        │        │\n",
            "                           (8, 3)───(8, 4)───(8, 5)\n",
            "                                    │\n",
            "                                    │\n",
            "                                    (9, 4)\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0YIaUjiK30TG"
      },
      "source": [
        "We will need to map our algorithm onto real qubits.  Let's examine the circuit for our exclusion queen move sequence again and look at the constraints.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "86v1X_e7BIyF",
        "outputId": "7aadd73a-1fdb-4423-f770-694912d49bc1",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "print(after_exclusion_without_measurement)"
      ],
      "execution_count": 123,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "                       ┌──────────────┐   ┌──────────┐\n",
            "a1: ───X───iSwap────────iSwap────────────────────────────────────\n",
            "           │            │\n",
            "a3: ───X───┼────────────┼───────────────────────iSwap────────────\n",
            "           │            │                       │\n",
            "b1: ───────iSwap^0.5────┼────iSwap─────────iSwap┼────────────────\n",
            "                        │    │             │    │\n",
            "b2: ────────────────────iSwap┼─────────────┼────iSwap────────────\n",
            "                             │             │\n",
            "c1: ─────────────────────────iSwap^0.5─────┼─────────────────────\n",
            "                                           │\n",
            "c2: ───────────────────────────────────────iSwap─────────iSwap───\n",
            "                                                         │\n",
            "c3: ─────────────────────────────────────────────────────iSwap───\n",
            "                       └──────────────┘   └──────────┘\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lnnjc8N81tOZ"
      },
      "source": [
        "First, one note is that this circuit uses iSWAP gates.  However, the sycamore device actually only supports $\\sqrt{\\text{iSWAP}}$ gates.  Luckily, an iSWAP is just two $\\sqrt{\\text{iSWAP}}$ gates in a row.  We will use cirq's concept of an optimizer in order to accomplish this."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KzgzMIVu2mkR",
        "outputId": "22cc37fa-0b72-4adb-ac6c-96f3b6020ba7",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "class IswapDecomposer(cirq.PointOptimizer):\n",
        "    \"\"\"Optimizer that decomposes iSWAPs into iSWAP ** 0.5 operations.\n",
        "    \"\"\"\n",
        "    \n",
        "    def optimization_at(self, circuit: cirq.Circuit, index: int,\n",
        "                        op: cirq.Operation\n",
        "                       ) -> Optional[cirq.PointOptimizationSummary]:\n",
        "        if op.gate == cirq.ISWAP:\n",
        "            # If this operation is an iSWAP, transform\n",
        "            new_ops = [cirq.ISWAP(*op.qubits) ** 0.5,\n",
        "                       cirq.ISWAP(*op.qubits) ** 0.5]\n",
        "            \n",
        "            # Clear_span = 1 signifies that only this op should be replaced.\n",
        "            # clear_qubits replaces only operations with these qubits.\n",
        "            # new_operations \n",
        "            return cirq.PointOptimizationSummary(clear_span=1,\n",
        "                                                 clear_qubits=op.qubits,\n",
        "                                                 new_operations=new_ops)\n",
        "        #  Exercise to the reader:\n",
        "        #  Can you add an additional condition to this function to replace\n",
        "        #  controlled-iSWAP operations with the decomposition we found above?\n",
        "\n",
        "exclusion_with_sqrt_iswaps = after_exclusion_without_measurement.copy()\n",
        "IswapDecomposer().optimize_circuit(exclusion_with_sqrt_iswaps)\n",
        "print(exclusion_with_sqrt_iswaps)"
      ],
      "execution_count": 124,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "                       ┌──────────────────┐               ┌──────────────────┐   ┌──────────────────┐\n",
            "a1: ───X───iSwap─────────────────iSwap────────iSwap─────────────────────────────────────────────────────────────────────────────\n",
            "           │                     │            │\n",
            "a3: ───X───┼─────────────────────┼────────────┼─────────────────────iSwap──────────────────iSwap────────────────────────────────\n",
            "           │                     │            │                     │                      │\n",
            "b1: ───────iSwap^0.5────iSwap────┼────────────┼────────────iSwap────┼─────────────iSwap────┼────────────────────────────────────\n",
            "                        │        │            │            │        │             │        │\n",
            "b2: ────────────────────┼────────iSwap^0.5────iSwap^0.5────┼────────iSwap^0.5─────┼────────iSwap^0.5────────────────────────────\n",
            "                        │                                  │                      │\n",
            "c1: ────────────────────iSwap^0.5──────────────────────────┼──────────────────────┼─────────────────────────────────────────────\n",
            "                                                           │                      │\n",
            "c2: ───────────────────────────────────────────────────────iSwap^0.5──────────────iSwap^0.5─────────────iSwap───────iSwap───────\n",
            "                                                                                                        │           │\n",
            "c3: ────────────────────────────────────────────────────────────────────────────────────────────────────iSwap^0.5───iSwap^0.5───\n",
            "                       └──────────────────┘               └──────────────────┘   └──────────────────┘\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "oToKpwY5BP68"
      },
      "source": [
        "We now have the circuit with only gates that are supported by the hardware.  Let's now focus our attention on mapping our logical qubits onto the Grid.\n",
        "\n",
        "By visualising the circuit in a diagram, it becomes obvious that there are several adjacency requirements, if we can only perform two-qubit operations that are next to each other:\n",
        "\n",
        "*   a1 and b1\n",
        "*   a1 and b2\n",
        "*   b1 and c1\n",
        "*   b1 and c2\n",
        "*   b2 and a3\n",
        "*   c2 and c3\n",
        "\n",
        "We can condense this somewhat into two chains, with only b1 in common:\n",
        "\n",
        "*   a3 - b2 - a1 - b1 - c2 - c3\n",
        "*   b1 - c1\n",
        "\n",
        "There are many ways to lay this out on a grid, but let's pick a central qubit (3,5) for b1 and lay out the qubits in a pattern that goes outward in three\n",
        "directions from there.\n",
        "\n",
        "*   a3 (6,5) - b2 (5,5) - a1 (4,5) - b1 (3,5) - c2 (2,5) - c3 (1,5)\n",
        "*   b1 (3,5) => c1 (3,6)\n",
        "\n",
        "Great.  Note that, for smaller devices or larger circuits, this may be a more complicated bending path.  \n",
        "\n",
        "**Exercise to the reader:**  What do we do if we cannot force the circuit into a grid?  (Hint: can you make use of a SWAP gate?)\n",
        "\n",
        "Let's put together a simple dictionary and translate this to a circuit that can run on grid qubits.  Note that we will need to do one other task as well: **iSWAP** is not a native operation to Sycamore, so we will need to change it into 2\n",
        "`ISWAP ** 0.5` gates.  We will use the concept of a  `Device`.  This is a cirq construct that can verify that our operations are valid for the device.  \n",
        "\n",
        "(For instance, try to change one of the qubits below to a qubit not on the device or not adjacent to its required neighbors).\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Lx8A7jzkDtUi",
        "outputId": "025b606e-e095-4189-cc04-9d035b4f1aee",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "qubit_translation = {\n",
        "    cirq.NamedQubit('a3') : cirq.GridQubit(6, 5),\n",
        "    cirq.NamedQubit('b2') : cirq.GridQubit(5, 5),\n",
        "    cirq.NamedQubit('a1') : cirq.GridQubit(4, 5),\n",
        "    cirq.NamedQubit('b1') : cirq.GridQubit(3, 5),\n",
        "    cirq.NamedQubit('c2') : cirq.GridQubit(2, 5),\n",
        "    cirq.NamedQubit('c3') : cirq.GridQubit(1, 5),\n",
        "    cirq.NamedQubit('c1') : cirq.GridQubit(3, 6),\n",
        "    # Not used except for measurement\n",
        "    cirq.NamedQubit('a2') : cirq.GridQubit(2, 4),\n",
        "    cirq.NamedQubit('b3') : cirq.GridQubit(3, 4),\n",
        "}\n",
        "\n",
        "\n",
        "def qubit_transformer(namedQubit: cirq.Qid) -> cirq.Qid:\n",
        "    \"\"\"Transform a namedQubit into a GridQubit using the mapping.\"\"\"\n",
        "    return qubit_translation[namedQubit]\n",
        "\n",
        "\n",
        "# First, modify the circuit so that ISWAP's become two ISWAP ** 0.5\n",
        "exclusion_move_sycamore = exclusion_with_sqrt_iswaps.with_device(\n",
        "    new_device=cirq.google.Sycamore, \n",
        "    qubit_mapping=qubit_transformer)\n",
        "print(exclusion_move_sycamore)"
      ],
      "execution_count": 125,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(1, 5): ───────────────────────────────────────────────────────────────────iSwap───────iSwap───────\n",
            "                                                                           │           │\n",
            "(2, 5): ───────────────────────────────────────────iSwap───────iSwap───────iSwap^0.5───iSwap^0.5───\n",
            "                                                   │           │\n",
            "(3, 5): ───────iSwap───────iSwap───────────────────iSwap^0.5───iSwap^0.5───────────────────────────\n",
            "               │           │\n",
            "(3, 6): ───────┼───────────iSwap^0.5───────────────────────────────────────────────────────────────\n",
            "               │\n",
            "(4, 5): ───X───iSwap^0.5───iSwap───────iSwap───────────────────────────────────────────────────────\n",
            "                           │           │\n",
            "(5, 5): ───────────────────iSwap^0.5───iSwap^0.5───iSwap───────iSwap───────────────────────────────\n",
            "                                                   │           │\n",
            "(6, 5): ───X───────────────────────────────────────iSwap^0.5───iSwap^0.5───────────────────────────\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aEjS2BggQ3ke"
      },
      "source": [
        "This new diagram shows how we can map the logical qubits representing 'squares' into a circuit with physical grid qubits that only uses adjacent qubits.  This circuit could then be run on a hardware device!\n",
        "\n",
        "**Exercise to the reader:**  Can you write the code to execute this circuit (in the simulator) and do the reverse translation back to logical named qubits to interpret the results as chess positions?"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vG9T-vbH5q4c"
      },
      "source": [
        "### Dynamic Qubit Mapping\n",
        "\n",
        "The first time, we mapped the qubits from `NamedQubit`s to `GridQubit`s by hand.  Can we map qubits automatically without this hand-tuned mapping?\n",
        "\n",
        "We will use a depth-first search to try to automatically map the qubits.  The following code snippet is a bit longer, but it will attempt to map a qubit, followed by mapping the qubits it is connected to.  \n",
        "\n",
        "For example, we will first map the square 'b1' to `GridQubit` (3, 5).  We then see that 'a1', 'c1', and 'c2' need to be adjacent to 'b1', so we then map them (and their adjacent squares, etc) next.  We repeat this until we finish mapping or until we get ourselves into an impossible situation."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "0HuUkJY77wVE",
        "outputId": "d616981b-b95c-4de5-a133-95a8c3dbbf05",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "def map_helper(cur_node: cirq.Qid,\n",
        "                mapping: Dict[cirq.Qid, cirq.GridQubit],\n",
        "                available_qubits: Set[cirq.GridQubit],\n",
        "                graph: Dict[cirq.Qid, Iterable[cirq.Qid]]) -> bool:\n",
        "    \"\"\"Helper function to construct mapping.\n",
        "    Traverses a graph and performs recursive depth-first\n",
        "    search to construct a mapping one node at a time.\n",
        "    On failure, raises an error and back-tracks until a\n",
        "    suitable mapping can be found.  Assumes all qubits in\n",
        "    the graph are connected.\n",
        "    \n",
        "    Args:\n",
        "        cur_node: node to examine.\n",
        "        mapping: current mapping of named qubits to `GridQubits`\n",
        "        available_qubits: current set of unassigned qubits\n",
        "        graph: adjacency graph of connections between qubits,\n",
        "            representing by a dictionary from qubit to adjacent qubits\n",
        "    Returns:\n",
        "        True if it was possible to map the qubits, False if not.\n",
        "    \"\"\"\n",
        "    # cur_node is the named qubit\n",
        "    # cur_qubit is the currently assigned GridQubit\n",
        "    cur_qubit = mapping[cur_node]\n",
        "\n",
        "    # Determine the list of adjacent nodes that still need to be mapped\n",
        "    nodes_to_map = []\n",
        "    for node in graph[cur_node]:\n",
        "        if node not in mapping:\n",
        "            # Unmapped node.\n",
        "            nodes_to_map.append(node)\n",
        "        else:\n",
        "            # Mapped adjacent node.\n",
        "            # Verify that the previous mapping is adjacent in the Grid.\n",
        "            if not mapping[node].is_adjacent(cur_qubit):\n",
        "                # Nodes previously mapped are not adjacent\n",
        "                # This is an invalid mapping\n",
        "                return False\n",
        "    if not nodes_to_map:\n",
        "        # All done with this node.\n",
        "        return True\n",
        "\n",
        "    # Find qubits that are adjacent in the grid\n",
        "    valid_adjacent_qubits = []\n",
        "    for a in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n",
        "        q = cur_qubit + a\n",
        "        if q in available_qubits:\n",
        "            valid_adjacent_qubits.append(q)\n",
        "\n",
        "    # Not enough adjacent qubits to map all qubits\n",
        "    if len(valid_adjacent_qubits) < len(nodes_to_map):\n",
        "        return False\n",
        "\n",
        "    # Only map one qubit at a time\n",
        "    # This makes back-tracking easier.\n",
        "    node_to_map = nodes_to_map[0]\n",
        "\n",
        "    for node_to_try in valid_adjacent_qubits:\n",
        "        # Add proposed qubit to the mapping\n",
        "        # and remove it from available qubits\n",
        "        mapping[node_to_map] = node_to_try\n",
        "        available_qubits.remove(node_to_try)\n",
        "\n",
        "        # Recurse\n",
        "        # Move on to the qubit we just mapped.\n",
        "        # Then, come back to this node and\n",
        "        # map the rest of the adjacent nodes\n",
        "        if not map_helper(node_to_map, mapping, available_qubits, graph):\n",
        "            del mapping[node_to_map]\n",
        "            available_qubits.add(node_to_try)\n",
        "            continue\n",
        "            \n",
        "        if not map_helper(cur_node, mapping, available_qubits, graph):\n",
        "            del mapping[node_to_map]\n",
        "            available_qubits.add(node_to_try)\n",
        "            continue\n",
        "        # We have succeeded in mapping the qubits!\n",
        "        return True\n",
        "    # All available qubits were not valid.\n",
        "    # Fail upwards and back-track if possible.\n",
        "    return False\n",
        "\n",
        "def qubit_mapping(circuit: cirq.Circuit,\n",
        "                  device: cirq.Device,\n",
        "                  start_qubit: cirq.Qid,\n",
        "                  mapped_qubit: cirq.Qid) -> Dict[cirq.Qid, cirq.GridQubit]:\n",
        "      \"\"\"Create a mapping from NamedQubits to Grid Qubits\n",
        "       This function analyzes the circuit to determine which\n",
        "       qubits need to be adjacent, then maps to the grid of the device\n",
        "       based on the generated mapping.\n",
        "      \"\"\"\n",
        "      # Build up an adjacency graph based on the circuits.\n",
        "      # Two qubit gates will turn into edges in the graph\n",
        "      g = {}\n",
        "      for m in circuit:\n",
        "          for op in m:\n",
        "                if len(op.qubits) == 2:\n",
        "                    q1, q2 = op.qubits\n",
        "                    if q1 not in g:\n",
        "                        g[q1] = []\n",
        "                    if q2 not in g:\n",
        "                        g[q2] = []\n",
        "                    if q2 not in g[q1]:\n",
        "                        g[q1].append(q2)\n",
        "                    if q1 not in g[q2]:\n",
        "                        g[q2].append(q1)\n",
        "      for q in g:\n",
        "            if len(g[q]) > 4:\n",
        "                raise ValueError(\n",
        "                    f'Qubit {q} needs more than 4 adjacent qubits!')\n",
        "\n",
        "      # Initialize mappings and available qubits\n",
        "      start_list = set(device.qubits)\n",
        "      start_list.remove(mapped_qubit)\n",
        "\n",
        "      mapping = {}\n",
        "      mapping[start_qubit] = mapped_qubit\n",
        "\n",
        "      map_helper(start_qubit, mapping, start_list, g)\n",
        "\n",
        "      if len(mapping) != len(g):\n",
        "            print('Warning: could not map all qubits!')\n",
        "\n",
        "      return mapping\n",
        "\n",
        "dynamic_mapping = qubit_mapping(exclusion_with_sqrt_iswaps,\n",
        "                    cirq.google.Sycamore,\n",
        "                    cirq.NamedQubit('b1'),\n",
        "                    cirq.GridQubit(3, 5))\n",
        "for q in dynamic_mapping:\n",
        "  print(f'Qubit {q} maps to {dynamic_mapping[q]}')\n",
        "dynamically_mapped_circuit = exclusion_with_sqrt_iswaps.with_device(\n",
        "    new_device=cirq.google.Sycamore, \n",
        "    qubit_mapping=lambda q: dynamic_mapping[q])\n",
        "print(dynamically_mapped_circuit)"
      ],
      "execution_count": 126,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Qubit b1 maps to (3, 5)\n",
            "Qubit a1 maps to (3, 6)\n",
            "Qubit b2 maps to (3, 7)\n",
            "Qubit a3 maps to (3, 8)\n",
            "Qubit c1 maps to (3, 4)\n",
            "Qubit c2 maps to (4, 5)\n",
            "Qubit c3 maps to (4, 6)\n",
            "                                                   ┌──────────────────┐   ┌──────────────────┐\n",
            "(3, 4): ───────────────────iSwap─────────────────────────────────────────────────────────────────────────────────────────\n",
            "                           │\n",
            "(3, 5): ───────iSwap───────iSwap^0.5────────────────iSwap──────────────────iSwap─────────────────────────────────────────\n",
            "               │                                    │                      │\n",
            "(3, 6): ───X───iSwap^0.5───iSwap───────iSwap────────┼──────────────────────┼─────────────────────────────────────────────\n",
            "                           │           │            │                      │\n",
            "(3, 7): ───────────────────iSwap^0.5───iSwap^0.5────┼────────iSwap─────────┼────────iSwap────────────────────────────────\n",
            "                                                    │        │             │        │\n",
            "(3, 8): ───X────────────────────────────────────────┼────────iSwap^0.5─────┼────────iSwap^0.5────────────────────────────\n",
            "                                                    │                      │\n",
            "(4, 5): ────────────────────────────────────────────iSwap^0.5──────────────iSwap^0.5─────────────iSwap───────iSwap───────\n",
            "                                                                                                 │           │\n",
            "(4, 6): ─────────────────────────────────────────────────────────────────────────────────────────iSwap^0.5───iSwap^0.5───\n",
            "                                                   └──────────────────┘   └──────────────────┘\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3d2ipo_MC91o"
      },
      "source": [
        "This time, we are able to map the qubits dynamically!  Now, if the device changes, or a qubit on the device becomes temporarily unusable, we can quickly adjust the mapping to compensate.\n",
        "\n",
        "***Exercise:*** Can you use this to map to the `Sycamore23` device instead?  What about onto the `Foxtail` device?\n",
        "\n",
        "***Exercise:*** Try to map qubits on different device layouts and with different sequences of moves.  Will this algorithm ever fail?  Can you adjust the functions above to correct for those cases?\n",
        "\n",
        "***Exercise:*** Can you transform the above code to use a breadth-first search instead of a depth-first search instead?"
      ]
    }
  ]
}
